<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="code-ia4sE56m4l">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">
  
  <link rel="stylesheet" href="/blog/lib/animate-css/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"tangmonk-meat.gitee.io","root":"/blog/","scheme":"Muse","version":"8.0.0-rc.4","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"path":"search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>

  <meta name="description" content="日志路径带来的痛点Java 项目中少不了要和log4j等日志框架打交道, 开发环境和生产环境下日志文件的输出路径总是不一致, 设置为绝对路径的方式缺少了灵活性, 每次变更项目路径都要修改文件, 目前想到的最佳实现方式是: 根据项目位置自动加载并配置文件路径. 本文借鉴 Tomcat 的配置方式 $&amp;#123;catalina.home&amp;#125;&#x2F;logs&#x2F;catalina.out, 通过相对路径">
<meta property="og:type" content="article">
<meta property="og:title" content="根据项目位置自动加载并配置文件路径">
<meta property="og:url" content="https://tangmonk-meat.gitee.io/blog/2021/08/02/%E6%A0%B9%E6%8D%AE%E9%A1%B9%E7%9B%AE%E4%BD%8D%E7%BD%AE%E8%87%AA%E5%8A%A8%E5%8A%A0%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84/index.html">
<meta property="og:site_name" content="唐僧肉BLOG">
<meta property="og:description" content="日志路径带来的痛点Java 项目中少不了要和log4j等日志框架打交道, 开发环境和生产环境下日志文件的输出路径总是不一致, 设置为绝对路径的方式缺少了灵活性, 每次变更项目路径都要修改文件, 目前想到的最佳实现方式是: 根据项目位置自动加载并配置文件路径. 本文借鉴 Tomcat 的配置方式 $&amp;#123;catalina.home&amp;#125;&#x2F;logs&#x2F;catalina.out, 通过相对路径">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-08-02T07:13:31.060Z">
<meta property="article:modified_time" content="2021-08-02T07:15:05.399Z">
<meta property="article:author" content="TANGMONK-MEAT">
<meta property="article:tag" content="log4j">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://tangmonk-meat.gitee.io/blog/2021/08/02/%E6%A0%B9%E6%8D%AE%E9%A1%B9%E7%9B%AE%E4%BD%8D%E7%BD%AE%E8%87%AA%E5%8A%A8%E5%8A%A0%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>根据项目位置自动加载并配置文件路径 | 唐僧肉BLOG</title>
  






  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <main class="main">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader">
        <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">唐僧肉BLOG</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录生活中的点点滴滴</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">44</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">17</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">38</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <section class="post-toc-wrap sidebar-panel">
          <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%97%A5%E5%BF%97%E8%B7%AF%E5%BE%84%E5%B8%A6%E6%9D%A5%E7%9A%84%E7%97%9B%E7%82%B9"><span class="nav-number">1.</span> <span class="nav-text">日志路径带来的痛点</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#log4j-properties%E6%96%87%E4%BB%B6%E7%9A%84%E9%85%8D%E7%BD%AE"><span class="nav-number">2.</span> <span class="nav-text">log4j.properties文件的配置</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BD%BB%E5%BA%95%E8%A7%A3%E5%86%B3%E7%97%9B%E7%82%B9"><span class="nav-number">3.</span> <span class="nav-text">彻底解决痛点</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8D%95%E7%8B%AC%E7%9A%84Java%E7%A8%8B%E5%BA%8F%E5%8C%85-%E9%9D%9EJava-Web%E9%A1%B9%E7%9B%AE"><span class="nav-number">3.1.</span> <span class="nav-text">单独的Java程序包 (非Java Web项目)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Web%E9%A1%B9%E7%9B%AE"><span class="nav-number">3.2.</span> <span class="nav-text">Web项目</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%99%84%E5%BD%95-%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8D%E9%A1%B9%E7%9B%AE%E3%80%81%E7%B1%BB%E8%B7%AF%E5%BE%84%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="nav-number">4.</span> <span class="nav-text">附录 - 获取当前项目、类路径的几种方式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="nav-number">5.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
      </section>
      <!--/noindex-->

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="TANGMONK-MEAT"
      src="https://s1.ax1x.com/2020/09/22/wOscW9.jpg">
  <p class="site-author-name" itemprop="name">TANGMONK-MEAT</p>
  <div class="site-description" itemprop="description">直到这一刻微笑着说话为止，我至少留下了一公升眼泪</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">44</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/TANGMONK-MEAT" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;TANGMONK-MEAT" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:2950371251@qq.com" title="E-Mail → mailto:2950371251@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/TANGMONK-MEAT" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;TANGMONK-MEAT" rel="noopener" target="_blank"><i class="iconfont icongitee-fill-round fa-fw"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.leancloud.cn/" title="LeanCloud → https:&#x2F;&#x2F;www.leancloud.cn" rel="noopener" target="_blank"><i class="iconfont iconCloudupload fa-fw"></i>LeanCloud</a>
      </span>
  </div>
  <div class="cc-license animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" class="cc-opacity" rel="noopener" target="_blank"><img src="/blog/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </section>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </header>

      
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/TANGMONK-MEAT" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div id="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


      <div class="main-inner">
        

        <div class="content post posts-expand">
          

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://tangmonk-meat.gitee.io/blog/2021/08/02/%E6%A0%B9%E6%8D%AE%E9%A1%B9%E7%9B%AE%E4%BD%8D%E7%BD%AE%E8%87%AA%E5%8A%A8%E5%8A%A0%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://s1.ax1x.com/2020/09/22/wOscW9.jpg">
      <meta itemprop="name" content="TANGMONK-MEAT">
      <meta itemprop="description" content="直到这一刻微笑着说话为止，我至少留下了一公升眼泪">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="唐僧肉BLOG">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          根据项目位置自动加载并配置文件路径
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-08-02 15:13:31 / 修改时间：15:15:05" itemprop="dateCreated datePublished" datetime="2021-08-02T15:13:31+08:00">2021-08-02</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/log4j2/" itemprop="url" rel="index"><span itemprop="name">log4j2</span></a>
                </span>
            </span>

          
            <span id="/blog/2021/08/02/%E6%A0%B9%E6%8D%AE%E9%A1%B9%E7%9B%AE%E4%BD%8D%E7%BD%AE%E8%87%AA%E5%8A%A8%E5%8A%A0%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84/" class="post-meta-item leancloud_visitors" data-flag-title="根据项目位置自动加载并配置文件路径" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2021/08/02/%E6%A0%B9%E6%8D%AE%E9%A1%B9%E7%9B%AE%E4%BD%8D%E7%BD%AE%E8%87%AA%E5%8A%A8%E5%8A%A0%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2021/08/02/%E6%A0%B9%E6%8D%AE%E9%A1%B9%E7%9B%AE%E4%BD%8D%E7%BD%AE%E8%87%AA%E5%8A%A8%E5%8A%A0%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>4.2k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>4 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="日志路径带来的痛点"><a href="#日志路径带来的痛点" class="headerlink" title="日志路径带来的痛点"></a>日志路径带来的痛点</h1><p>Java 项目中少不了要和log4j等日志框架打交道, 开发环境和生产环境下日志文件的输出路径总是不一致, 设置为绝对路径的方式缺少了灵活性, 每次变更项目路径都要修改文件, 目前想到的最佳实现方式是: <strong>根据项目位置自动加载并配置文件路径</strong>.</p>
<p>本文借鉴 Tomcat 的配置方式 <code>$&#123;catalina.home&#125;/logs/catalina.out</code>, 通过相对路径的方式设置日志的输出路径。</p>
<a id="more"></a>

<h1 id="log4j-properties文件的配置"><a href="#log4j-properties文件的配置" class="headerlink" title="log4j.properties文件的配置"></a>log4j.properties文件的配置</h1><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置要输出的日志的级别 - 注意: properties文件中的注释信息只能处于行首, 不要跟在行尾</span></span><br><span class="line"><span class="meta">log4j.rootLogger</span>=<span class="string">INFO,stdout,logfile</span></span><br><span class="line"></span><br><span class="line"><span class="comment">### 输出到控制台, Java程序运行时的标准输出信息</span></span><br><span class="line"><span class="meta">log4j.appender.stdout</span>=<span class="string">org.apache.log4j.ConsoleAppender</span></span><br><span class="line"><span class="meta">log4j.appender.stdout.Target</span>=<span class="string">System.out</span></span><br><span class="line"><span class="meta">log4j.appender.stdout.layout</span>=<span class="string">org.apache.log4j.PatternLayout</span></span><br><span class="line"><span class="comment"># 2019-05-25 19:09:46</span></span><br><span class="line"><span class="meta">log4j.appender.stdout.layout.ConversionPattern</span>=<span class="string">%-d&#123;yyyy-MM-dd HH:mm:ss&#125; [%t] [%c] [%p] - %m%n</span></span><br><span class="line"></span><br><span class="line"><span class="comment">### 输出到日志文件</span></span><br><span class="line"><span class="comment"># 按天滚动生成, 不支持MaxFileSize, 而RollingFileAppender支持</span></span><br><span class="line"><span class="meta">log4j.appender.logfile</span>=<span class="string">org.apache.log4j.DailyRollingFileAppender</span></span><br><span class="line"><span class="comment"># 项目的logs目录下</span></span><br><span class="line"><span class="comment"># log4j.appender.logfile.File=$&#123;base.dir&#125;/logs/elastic-server.log</span></span><br><span class="line"><span class="meta">log4j.appender.logfile.Append</span>=<span class="string">true</span></span><br><span class="line"><span class="comment"># 输出INFO及以上的日志, 按日期滚动就无须配置单个日志文件的最大体积了</span></span><br><span class="line"><span class="meta">log4j.appender.logfile.Threshold</span>=<span class="string">INFO</span></span><br><span class="line"><span class="comment"># log4j.appender.logfile.MaxFileSize=100MB</span></span><br><span class="line"><span class="meta">log4j.appender.logfile.layout</span>=<span class="string">org.apache.log4j.PatternLayout</span></span><br><span class="line"><span class="meta">log4j.appender.logfile.layout.ConversionPattern</span>=<span class="string">%-d&#123;yyyy-MM-dd HH:mm:ss&#125; [%t] [%c] [%p] - %m%n</span></span><br></pre></td></tr></table></figure>

<h1 id="彻底解决痛点"><a href="#彻底解决痛点" class="headerlink" title="彻底解决痛点"></a>彻底解决痛点</h1><h2 id="单独的Java程序包-非Java-Web项目"><a href="#单独的Java程序包-非Java-Web项目" class="headerlink" title="单独的Java程序包 (非Java Web项目)"></a>单独的Java程序包 (非Java Web项目)</h2><p>单独的Java程序包, 需要通过命令<code>java -jar</code>或<code>java -cp</code>的方式启动;</p>
<p>我们可以在启动命令中加入系统运行时变量, 在log4j加载配置文件之前通过<code>System.getProperties(&quot;path&quot;)</code>读取此变量, 即可实现灵活加载当前路径.</p>
<ol>
<li>启动脚本设置:</li>
</ol>
<p>假设当前项目的目录结构为:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;Projects&#x2F;KafkaConsumer</span><br><span class="line">                      丨 bin   项目的启动脚本</span><br><span class="line">                      丨 conf  项目的配置文件</span><br><span class="line">                      丨 lib   项目的其他依赖包</span><br><span class="line">                      丨 bogs  项目的日志输出路径</span><br></pre></td></tr></table></figure>

<p>启动脚本位于bin目录下, 内容示例如下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"># 获取当前脚本所处的目录, 然后进入其上级目录, 最后pwd输出该目录, 最终的结果是&#x2F;Project&#x2F;KafkaConsumer</span><br><span class="line">base_dir&#x3D;$(cd &#96;dirname $0&#96;; cd ..; pwd)</span><br><span class="line"># 获取Java运行程序的位置, 并指定主类</span><br><span class="line">java_bin&#x3D;$(which java)</span><br><span class="line">main_class&#x3D;&quot;org.shoufeng.elastic.ConsumerMain&quot;</span><br><span class="line"></span><br><span class="line"># 通过-cp、扩展CLASSPATH、指定主类的方式启动项目, </span><br><span class="line"># 并通过“-D”的方式向此程序的运行时环境中设置当前项目的路径,</span><br><span class="line"># 即可在程序中通过System.getProperty(&quot;base.dir&quot;)获取此路径 </span><br><span class="line"></span><br><span class="line">nohup $&#123;java_bin&#125; -Dbase.dir&#x3D;$&#123;base_dir&#125; -cp $&#123;CLASSPATH&#125;:$&#123;base_dir&#125;&#x2F;conf:$&#123;base_dir&#125;&#x2F;lib&#x2F;* $&#123;main_class&#125; &gt;&gt; &#x2F;dev&#x2F;null &amp;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>Java程序读取变量:</li>
</ol>
<p>log4j的FileAppender本身支持动态设置文件路径, 如:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">log4j.appender.logfile.File&#x3D;$&#123;base.log&#125;&#x2F;logs&#x2F;app.log </span><br></pre></td></tr></table></figure>

<p>其中<code>$&#123;base.log&#125;</code>是一个变量, 会被System Property中的base.log的值代替, 代码中的使用方式为:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取系统运行时变量中的日志文件的输出路径</span></span><br><span class="line">    <span class="comment">// 此变量需要在启动命令中通过-D的方式设置</span></span><br><span class="line">    String baseDir = System.getProperty(<span class="string">&quot;base.dir&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span> (baseDir == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// 开发环境中使用</span></span><br><span class="line">        baseDir = System.getProperty(<span class="string">&quot;user.dir&quot;</span>);</span><br><span class="line">        System.setProperty(<span class="string">&quot;base.dir&quot;</span>, baseDir);</span><br><span class="line">    &#125;</span><br><span class="line">    log.info(<span class="string">&quot;==== 系统运行路径: &quot;</span> + System.getProperty(<span class="string">&quot;base.dir&quot;</span>) + <span class="string">&quot; ====&quot;</span>);</span><br><span class="line">    <span class="comment">// 其他处理逻辑......</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意：这种方式设置的环境变量只在当前Java进程(也就是当前项目)中有效, 并不会影响到其他项目.</p>
</blockquote>
<h2 id="Web项目"><a href="#Web项目" class="headerlink" title="Web项目"></a>Web项目</h2><p>如果是Web项目, 可通过修改Web容器的环境变量方式实现. 以 Tomcat 为例:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"># log4j的配置文件支持服务器的vm环境变量, 格式类似$&#123;catalina.home&#125; </span><br><span class="line">log4j.appender.R&#x3D;org.apache.log4j.RollingFileAppender </span><br><span class="line">log4j.appender.R.File&#x3D;$&#123;catalina.home&#125;&#x2F;logs&#x2F;logs_tomcat.log </span><br><span class="line">log4j.appender.R.MaxFileSize&#x3D;100MB </span><br><span class="line">$&#123;catalina.home&#125;是在$&#123;tomcat_home&#125;&#x2F;bin&#x2F;catalina.sh中通过-D参数设置的:</span><br><span class="line"></span><br><span class="line">-Dcatalina.home&#x3D;&quot;$CATALINA_HOME&quot;</span><br><span class="line">基于这个思路, 我们也可以向Web容器的VM参数中设置一个参数, 比如-Dmylog.home&#x3D;&quot;&#x2F;Project&#x2F;logs&quot;, 创建日志对象时即可使用.</span><br></pre></td></tr></table></figure>

<h1 id="附录-获取当前项目、类路径的几种方式"><a href="#附录-获取当前项目、类路径的几种方式" class="headerlink" title="附录 - 获取当前项目、类路径的几种方式"></a>附录 - 获取当前项目、类路径的几种方式</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获取 class 文件的绝对路径, 定位到具体的包名, 结果如: </span></span><br><span class="line">    <span class="comment">// /Projects/KafkaConsumer/target/classes/org/shoufeng/consumer/</span></span><br><span class="line">    System.out.println(KafkaConsumer.class.getResource(<span class="string">&quot;&quot;</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取 class 文件的绝对路径, 如: /Projects/KafkaConsumer/target/classes/,</span></span><br><span class="line">    <span class="comment">// 如果在bin目录下通过java -jar等命令启动时, 结果就是 /Projects/KafkaConsumer/bin/</span></span><br><span class="line">    System.out.println(ClassLoader.getSystemResource(<span class="string">&quot;&quot;</span>));</span><br><span class="line">    System.out.println(KafkaConsumer.class.getResource(<span class="string">&quot;/&quot;</span>));</span><br><span class="line">    System.out.println(KafkaConsumer.class.getClassLoader().getResource(<span class="string">&quot;&quot;</span>));</span><br><span class="line">    System.out.println(Thread.currentThread().getContextClassLoader().getResource(<span class="string">&quot;&quot;</span>));</span><br><span class="line">    <span class="comment">// 说明: 上述4种用法的返回结果类型都是URL, 其toString()返回的内容以&quot;file:&quot;开头, 可通过“.toString().substring(5)”去除</span></span><br><span class="line">    <span class="comment">// 推荐: 使用“.getPath()”就可以直接获取到路径</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获取工程的绝对路径, 如: /Projects/KafkaConsumer,</span></span><br><span class="line">    <span class="comment">// 若在bin中通过java -jar等命令启动, 路径就变成了: /Projects/KafkaConsumer/bin</span></span><br><span class="line">    System.out.println(System.getProperty(<span class="string">&quot;user.dir&quot;</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/leihenqianshang/articles/4153270.html">log4j 产生的日志位置设置 和 catalina.home、catalina.base</a></p>

    </div>

     <!-- 文章结束表示语-->
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
      
    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>TANGMONK-MEAT
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://tangmonk-meat.gitee.io/blog/2021/08/02/%E6%A0%B9%E6%8D%AE%E9%A1%B9%E7%9B%AE%E4%BD%8D%E7%BD%AE%E8%87%AA%E5%8A%A8%E5%8A%A0%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84/" title="根据项目位置自动加载并配置文件路径">https://tangmonk-meat.gitee.io/blog/2021/08/02/根据项目位置自动加载并配置文件路径/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/log4j/" rel="tag"><i class="fa fa-tag"></i> log4j</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2021/03/19/%E5%A4%9A%E7%BA%A7%E5%8F%8D%E9%A6%88%E9%98%9F%E5%88%97%E8%B0%83%E5%BA%A6%E7%AE%97%E6%B3%95/" rel="prev" title="多级反馈队列调度算法">
      <i class="fa fa-chevron-left"></i> 多级反馈队列调度算法
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  



        </div>
        
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">TANGMONK-MEAT</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">148k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">2:15</span>
</div>

<!--
-->

<!--<div>
<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span> 
 <span class="post-meta-divider">|</span> 
 <span class="post-meta-item-icon">
<span id="busuanzi_container_site_uv">
  本站访客数<span id="busuanzi_value_site_uv"></span>人次
</span>
</div> 

-->




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/muse.js"></script>


<script src="/blog/js/next-boot.js"></script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/blog/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments('#valine-comments', () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', () => {
    new Valine(Object.assign({
      el  : '#valine-comments',
      path: location.pathname,
    }, {"enable":true,"appId":"dkMV7sEQR97E6CWI5jduGKf3-gzGzoHsz","appKey":"JQfXJ0ELtfNma5bdMQk0vgwX","placeholder":"ヾﾉ≧∀≦)o来啊，快活啊!","avatar":"mm","meta":["nick","mail"],"pageSize":10,"language":"zh-cn","visitor":true,"comment_count":true,"recordIP":true,"serverURLs":null,"enableQQ":false,"requiredFields":[]}
    ));
  }, window.Valine);
});
</script>

</body>
</html>
